/*
 * Copyright (c) 2012-2013, Yunnan Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package net.jeeshop.web.action.phone;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.jeeshop.app.appobject.FileInfoAO;
import net.jeeshop.app.dao.gen.FileInfoGeneratedMapper;
import net.jeeshop.app.entity.gen.FileInfoCriteria;
import net.jeeshop.services.front.account.AccountService;
import net.jeeshop.services.front.account.bean.Account;
import net.jeeshop.services.front.catalog.CatalogService;
import net.jeeshop.services.front.catalog.bean.Catalog;
import net.jeeshop.services.front.order.bean.Order;
import net.jeeshop.services.front.product.ProductService;
import net.jeeshop.services.front.product.bean.Product;
import net.jeeshop.services.manage.attribute_link.Attribute_linkService;
import net.jeeshop.services.manage.attribute_link.bean.Attribute_link;
import net.jeeshop.services.manage.product.bean.ProductSx;
import net.jeeshop.web.util.SingleLoginUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuanxin.service.biz.schuserbase.appobject.OrganMemberEntityAO;
import com.yuanxin.service.biz.schuserbase.util.SchUserUtil;

/**
 * Hello控制器。
 * 
 */
@Controller
@RequestMapping(value = "/phone/home")
public class HomeController {

	private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(HomeController.class);
	@Resource
	private AccountService accountService;
	@Resource
	private ProductService productService;
	@Resource
	private CatalogService catalogService;
	@Autowired
	private Attribute_linkService attribute_linkService;
	@Resource
	private SingleLoginUtil singleLoginUtil;
	/**
	 * 图片
	 */
    @Resource
    private FileInfoGeneratedMapper fileInfoGeneratedMapper;
    
	 //private static final String page_toList = "/phone/list";
	 private static final String page_toIndex = "/phone/index";
	 private static final String page_detail = "/phone/detail";
	 
    @RequestMapping(value = "", method = { RequestMethod.GET, RequestMethod.POST })
    public String home(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        String token = request.getParameter("token");
        //获取热门商品列表
        List<List<Product>> hotRes = new ArrayList<List<Product>>();
        List<List<Product>> tjRes = new ArrayList<List<Product>>();
        List<Catalog> hotCatalogs = new ArrayList<Catalog>();
        Catalog cata = new Catalog();
        cata.setPid("0");
        cata.setType("p");
        cata.setShowInNav("y");
        cata.setHotflag("y");
        hotCatalogs = catalogService.selectList(cata);
        model.addAttribute("hotCatalogs", hotCatalogs);
        Product p1= new Product();
        Product p2= new Product();
        Product p3= new Product();
        List<Product> hotProduceList = loadProducts(3);
        //热门商品获取出前三个，特殊显示
        if(hotProduceList!= null && !hotProduceList.isEmpty() && hotProduceList.size() >0){
        	p1 = hotProduceList.get(0);
        	model.addAttribute("p1", p1);
        }
        if(hotProduceList!= null && !hotProduceList.isEmpty() && hotProduceList.size() >1){
        	p2 = hotProduceList.get(1);
        	 model.addAttribute("p2", p2);
        }
        if(hotProduceList!= null && !hotProduceList.isEmpty() && hotProduceList.size() >2){
        	p3 = hotProduceList.get(2);
        	model.addAttribute("p3", p3);
        }
        if(hotProduceList!= null && !hotProduceList.isEmpty() && hotProduceList.size() >3){
        	for(int i=0;i<=2;i++){
        		hotProduceList.remove(0);
        	}
        	//hotRes = convert(hotProduceList,3);
        }
    	//model.addAttribute("hotProduceList", hotRes);
        model.addAttribute("hotProduceList", hotProduceList);
        //获取推介商品列表
        List<Product> tjProduceList = loadProducts(4);
        //tjRes = convert(tjProduceList,2);
        //model.addAttribute("tjProduceList", tjRes);
        model.addAttribute("tjProduceList", tjProduceList);
        //提取分类信息
        retrieval(model);
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "商城首页");
        model.addAttribute("token", token);
       LOG.info("手机端 访问结束");
        return page_toIndex;
    }
    
    @RequestMapping(value = "/detail", method = { RequestMethod.GET, RequestMethod.POST })
    public String detail(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前运用名称传到前端
        String productId = request.getParameter("productId");
        Product pp = new Product();
        Catalog cc = new Catalog();
        if(StringUtils.isNotBlank(productId)){
        	pp = productService.selectById(productId);
        	
        }
        if(pp != null){
        	cc.setId(pp.getCatalogID());
        	cc = catalogService.selectOne(cc);
        	
        }
      //加载固定属性列表 
  		ProductSx psx = new ProductSx();
  		Attribute_link aa = new Attribute_link();
  		if(pp != null && StringUtils.isNotBlank(pp.getId())){
  			aa.setAttrID(0);
      		aa.setProductID(Integer.parseInt(pp.getId()));
      		List<Attribute_link> resList = attribute_linkService.selectList(aa);
      		if(resList != null && !resList.isEmpty()){
      			for(Attribute_link en : resList){
      				if(en != null && StringUtils.isNotBlank(en.getValue())){
      					String[] arr = en.getValue().split(":");
      					if(arr.length == 2){
      						String attr = arr[0];
      						String value = arr[1];
      						if("cpxl".equals(attr)){
      							psx.setCpxl(value);
      						}
      						if("zz".equals(attr)){
      							psx.setZz(value);
      						}
      						if("sftz".equals(attr)){
      							psx.setSftz(value);
      						}
      						if("cbsj".equals(attr)){
      							psx.setCbsj(value);
      						}
      						if("bh".equals(attr)){
      							psx.setBh(value);
      						}
      					}
      				}
      			}
      		}
      		psx.setCpmc(pp.getName());
      		psx.setCbsmc(pp.getCbs());
      		psx.setSpId(pp.getId());
  		}
  		List<String> imagesList = new LinkedList<String>();
		FileInfoCriteria example = new FileInfoCriteria();
		example.createCriteria().andFormIdEqualTo(pp.getId());
		List<FileInfoAO> list =	fileInfoGeneratedMapper.selectByCriteria(example);
		if(list.size()>0){
			for(FileInfoAO f:list){
				imagesList.add(f.getFileId());
			}
			pp.setImageList(imagesList);
		}else{
			if(pp.getImageList()==null){
				pp.setImageList(Collections.EMPTY_LIST);
			}else{
				pp.getImageList().clear();
			}
		}
		
      	model.addAttribute("psx",psx);
        model.addAttribute("e", pp);
        model.addAttribute("cc", cc);
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "商品详情");
        return page_detail;
    }
    
 // 加载商品
 	private List<Product> loadProducts(int type) {
 		Product p = new Product();
 		p.setTop(8);//控制获取条目
 		if (type == 1) {
 			p.setIsnew(Product.Product_isnew_y);//最新
 		} else if (type == 2) {
 			p.setSale(Product.Product_sale_y);//特价
 		} else if (type == 3) {
 			p.setHot(true);//热门
 		}else if (type == 4) {
 			p.setTjcs(1);//推介商品
 		}
 		return productService.selectList(p);
 	}
 	
 	/**
 	 * 适应商品每行显示数
 	 * 
 	 * */
 	private List<List<Product>> convert(List<Product> result,int rowSize){
		if(result==null || result.size()==0){
			return null;
		}
		List<List<Product>> list = new LinkedList<List<Product>>();
		int nn = 0;
		int maxLen = rowSize;
		List<Product> row = new LinkedList<Product>();
		for(int i=0;i<result.size();i++){
			Product ee = result.get(i);
			row.add(ee);
			nn++;
			list.add(row);
			/*if(nn==maxLen){
				list.add(row);
				nn=0;
				row = new LinkedList<Product>();
			}
			
			if(result.size()==i+1){
				if(row.size()==0){
					row.add(ee);
				}
				list.add(row);
			}*/
			
		}
		return list;
 		}
 	
 	
 	/**
     * 搜索结果-检索
     * 获取所有分类，父类和子类
     * 
     * **/
    public void retrieval(Model model){
    	//获取分类一
    	Catalog e = new Catalog();
    	e.setType("p");
    	e.setShowInNav("y");
    	e.setHotflag("y");
    	e.setPid("0");
    	List<Catalog> rootList = new ArrayList<Catalog>();
    	List<Catalog> childrenList = new ArrayList<Catalog>();
    	List<Catalog> catalogList = catalogService.selectList(e);
    	for(Catalog ao : catalogList){
    		if("0".equals(ao.getPid())){
    			rootList.add(ao);
    		}
    	}
    	for(Catalog ao : rootList) {
    		e.clear();
    		e.setPid(ao.getId());
    		catalogList = catalogService.selectList(e);
    		if(null != catalogList && !catalogList.isEmpty() && catalogList.size() > 0) {
    			childrenList.addAll(catalogList);
    		}
    	}
    	//获取出版社信息
    	e.clear();
    	e.setType("ss");
    	e.setPid("0");
    	e.setShowInNav("y");
    	List<Catalog> catalogCbsList = catalogService.selectList(e);
    	
    	model.addAttribute("rootList", rootList);
    	model.addAttribute("childrenList", childrenList);
    	model.addAttribute("catalogCbsList", catalogCbsList);

    }
    /**
     * 校验用户是否登录
     * 
     * */
    @RequestMapping(value = "/checkLogin", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object checkLogin(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String res = "false";
    	Account acc = new Account();
        String token = request.getParameter("token");
        if(StringUtils.isBlank(token)){
        	return res;
        }else{
        	acc = singleLoginUtil.singleLogin(token);
        }
        if(acc != null && StringUtils.isNotBlank(acc.getId())){
        	res = "true";
        }
        return  res;
    }
}